/**
 * Created by Administrator on 2019/1/26.
 */
'use strict';
const Controller = require('egg').Controller;
const fs = require('fs');
const pinyin = require('js-pinyin');
const config = require('../utils/config');
const uploadRecord = require('../utils/store').uploadRecord;

class LoginController extends Controller {

  /**
   * 上传报销excel
   */
  async uploadFile() {
    this.saveFile(this.ctx);
  }

  /**
   * 上传滴滴发票与行程
   */
  async uploadDidi() {
    this.saveFile(this.ctx);
    const name = this.ctx.session.name;
    if (uploadRecord[name]) {
      uploadRecord[name].isCarUpload = true;
    }
  }

  saveFile(ctx) {
    ctx.request.files.forEach(file => {
      const filename = file.filename;
      fs.mkdir(`${config.fileDir}/user/${pinyin.getFullChars(ctx.session.name)}`, function(err) {
        const data = fs.readFileSync(file.filepath);
        fs.writeFileSync(`${config.fileDir}/user/${pinyin.getFullChars(ctx.session.name)}/${filename}`, data);
      });
      ctx.body = 1;
    });
  }

  /**
   * 上传餐饮发票
   */
  async uploadFood() {
    const { ctx } = this;
    ctx.request.files.forEach(file => {
      const filename = pinyin.getFullChars(file.filename);
      fs.mkdir(`${config.fileDir}/foodFaPiao`, function(err) {
        const data = fs.readFileSync(file.filepath);
        fs.writeFileSync(`${config.fileDir}/foodFaPiao/${filename}`, data);

        const name = ctx.session.name;
        if (uploadRecord[name]) {
          uploadRecord[name].isFapiaoUpload = true;
        }
      });
      ctx.body = 1;
    });
  }
}

module.exports = LoginController;
